<template>
  <div class="head-container">
    <el-input v-model="deptName" class="mb-20px" clearable placeholder="请输入数据库名称">
      <template #prefix>
        <Icon icon="ep:search" />
      </template>
    </el-input>
    <el-button
      @click="openForm('create')"
      v-hasPermi="['sys:databasesharing:create']"
    ><Icon icon="ep:plus" /></el-button>
  </div>
  <div class="container">
    <el-tree
      ref="treeRef"
      :data="baseList"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      :props="defaultProps"
      default-expand-all
      highlight-current
      node-key="id"
      @node-click="handleNodeClick"
    >
      <template #default="{ data }">
        <div class="custom-tree-node ellipsis ellipsis-1">
          <el-tooltip>
            <template #content>
              <el-button
                link
                type="primary"
                @click="openForm('update', data.id)"
                v-hasPermi="['infra:data-source-config:update']"
                :disabled="data.id === 0"
              >
                编辑
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(data.id)"
                v-hasPermi="['infra:data-source-config:delete']"
                :disabled="data.id === 0"
              >
                删除
              </el-button>
            </template>
            <span class="node-name">{{ data.name }}</span>
          </el-tooltip>
        </div>
      </template>
    </el-tree>

    <!-- 表单弹窗：添加/修改 -->
    <DataSourceConfigForm ref="formRef" @success="getTree" />
  </div>
</template>

<script lang="ts" setup>
import { ElTree } from 'element-plus'
import * as DataSourceConfigApi from '@/api/infra/dataSourceConfig'
import { defaultProps, handleTree } from '@/utils/tree'

defineOptions({ name: 'DatabaseTree' })
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const emits = defineEmits(['update:modelValue', 'node-click'])
const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: undefined
  }
})
const deptName = ref('')
const baseList = ref<Tree[]>([]) // 树形结构
const treeRef = ref<InstanceType<typeof ElTree>>()

/** 获得部门树 */
const getTree = async () => {
  const res = await DataSourceConfigApi.getDataSourceConfigList()
  baseList.value = []
  baseList.value.push(...handleTree(res))
}

/** 基于名字过滤 */
const filterNode = (name: string, data: Tree) => {
  if (!name) return true
  return data.name.includes(name)
}

/** 处理部门被点击 */
const handleNodeClick = async (row: { [key: string]: any }) => {
  emits('update:modelValue', row.id)
  emits('node-click', row)
}

/** 监听deptName */
watch(deptName, (val) => {
  treeRef.value!.filter(val)
})

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DataSourceConfigApi.deleteDataSourceConfig(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getTree()
  } catch {}
}


/** 初始化 */
onMounted(async () => {
  await getTree()
})
</script>

<style lang="scss" scoped>
.head-container {
  display: flex;
}
</style>